﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Text.RegularExpressions;
using System.Configuration;

namespace Beeldbankmvc.Helpers
{
    public class ImageRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string filename = requestContext.RouteData.Values["filename"] as string;

            if (string.IsNullOrEmpty(filename))
            {
                // return a 404 HttpHandler here
            }
            else
            {
                String pictureName = filename;

                requestContext.HttpContext.Response.Clear();
                requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString());
                
                string regex = "\\[([0-9]*)x([0-9]*)-([0-9]*)\\]";
                RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
                Regex reg = new Regex(regex, options);

                Match match = reg.Match(pictureName);

                int intWidth = 0;
                int intHeight = 0;
                int MediaObjectId = 0;

                if (match.Success)
                {
                    intWidth = Convert.ToInt32(match.Groups[1].Value);
                    intHeight = Convert.ToInt32(match.Groups[2].Value);
                    MediaObjectId = Convert.ToInt32(match.Groups[3].Value);
                }

                // Determine first part of the filename
                int mapNumber = MediaObjectId / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
                // Determine first part of the filename
                string fileName = "";
                string fileNameScaledImage = "";
                fileName = ConfigurationManager.AppSettings["FotoArchive"] + "\\" + mapNumber.ToString();
                // Check if directory exists
                Tools.CheckDir(fileName);
                // Creeer de nieuwe filenaam en forceer de juiste extensie
                // Complete the filename for the full version
                fileNameScaledImage = fileName + "\\" + MediaObjectId.ToString() + "_[" + intWidth + "x" + intHeight + "].jpg";
                bool exists = System.IO.File.Exists(fileNameScaledImage);

                Image TridionImage = null;

                if (!exists)
                {
                    Bitmap objBmpImage = new Bitmap(1, 1);

                    // Create the Font object for the image text drawing.
                    Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
                    // Create a graphics object to measure the text's width and height.
                    Graphics objGraphics = Graphics.FromImage(objBmpImage);
                    // This is where the bitmap size is determined.
                    if (intWidth == 0 || intHeight == 0)
                    {
                        intWidth = (int)objGraphics.MeasureString(pictureName, objFont).Width;
                        intHeight = (int)objGraphics.MeasureString(pictureName, objFont).Height;
                    }
                    // Create the bmpImage again with the correct size for the text and font.
                    objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
                    // Add the colors to the new bitmap.
                    
                    objBmpImage = new Bitmap(Image.FromFile(fileName + "\\" + MediaObjectId.ToString() + ".jpg"), new Size(intWidth, intHeight));

                    objGraphics = Graphics.FromImage(objBmpImage);
                    // Set Background color
                    //objGraphics.Clear(Color.White);
                    objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                    objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                    objGraphics.DrawString(pictureName, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
                    objGraphics.Flush();

                    TridionImage = objBmpImage;
                    TridionImage.Save(fileNameScaledImage);
                }
                else
                {
                    Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

                    // load existing file
                    Bitmap objBmpImage = new Bitmap(fileName);

                    Graphics objGraphics = Graphics.FromImage(objBmpImage);
                    objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                    objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                    objGraphics.DrawString("[cached]", objFont, new SolidBrush(Color.FromArgb(102, 0, 0)), 100, 100);
                    objGraphics.Flush();

                    TridionImage = objBmpImage;
                }

                // find physical path to image here.  
                //string filepath = requestContext.HttpContext.Server.MapPath("~/test.jpg");

                requestContext.HttpContext.Response.WriteFile(fileName);
                requestContext.HttpContext.Response.End();
            }
            return null;
        }

        private static string GetContentType(String path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp": return "Image/bmp";
                case ".gif": return "Image/gif";
                case ".jpg": return "Image/jpeg";
                case ".png": return "Image/png";
                default: break;
            }
            return "";
        }
    }
}